package main

import (
	"context"
	"fmt"
	"grpc-test/config"
	"grpc-test/rpc"
	"sync"

	"go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/naming/resolver"
	"google.golang.org/grpc/balancer/roundrobin"
	"google.golang.org/grpc/credentials/insecure"

	"google.golang.org/grpc"
)

func main() {
	// 获取etcd服务
	etcdClient, err := clientv3.New(clientv3.Config{
		Endpoints: []string{config.EtcdUrl},
	})

	if err != nil {
		panic(err)
	}
	builder, err := resolver.NewBuilder(etcdClient)
	if err != nil {
		panic(err)
	}

	// 与etcd建立连接
	conn, err := grpc.Dial("etcd:///"+config.ServiceName, grpc.WithResolvers(builder), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)))
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	
	// 创建客户端
	client := rpc.NewCalculationClient(conn)
	// 调用远程NumInit函数
	res, err := client.NumInit(context.Background(), &rpc.Empty{})
	if err != nil {
		panic(err)
	}
	num := res.I
	println("rand number:", num)
	wg := new(sync.WaitGroup)
	
	count := num / 10
	ress := make([]uint64, count)
	var i uint32
	for i = 10; i < num; i += 10 {
		wg.Add(1)
		j := i
		go func() {
			// 与etcd建立连接
			conn, err := grpc.Dial("etcd:///"+config.ServiceName, grpc.WithResolvers(builder), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)))
			if err != nil {
				panic(err)
			}
			defer conn.Close()
			defer wg.Done()
			// 创建客户端
			client := rpc.NewCalculationClient(conn)
			
			res, err := client.Plus(context.Background(), &rpc.NumReq{I: j})
			ress[j/10 -1] = res.I
		}()
	}

	var result uint64 = 0
	{
		r, err := client.Plus(context.Background(), &rpc.NumReq{I: num})
		if err != nil {
			panic(err)
		}
		result = r.I	
	}
	wg.Wait()
	// marge
	var tmp uint64 = 0
	for _, res := range ress {
		tmp += res
	}
	println("1 + ... +", num, "=", result + tmp)
}
